package zy;

import java.util.function.IntConsumer;

public class ZeroEvenOdd {
	int n;
	public volatile int flag = 1;

	public ZeroEvenOdd(int n) {
		super();
		this.n = n;
	}

	public void zero(IntConsumer printer) throws Exception {
		for (int i = 1; i <= n; i++) {
			synchronized (this) {
				while (flag % 2 == 0) {
					this.wait();
				}
				flag++;
				printer.accept(0);
				this.notifyAll();
			}
		}
	}
	public void even(IntConsumer printer) throws Exception {
		for (int i = 2; i <= n; i += 2) {
			synchronized (this) {
				while (flag % 4 != 0) {
					this.wait();
				}
				flag++;
				printer.accept(i);
				this.notifyAll();
			}
		}
	}

	public void odd(IntConsumer printer) throws Exception {
		for (int i = 1; i <= n; i += 2) {
			synchronized (this) {
				while (flag % 4 != 2) {
					this.wait();
				}
				printer.accept(i);
				flag++;
				this.notifyAll();
			}
		}
	}

	public static void printNumber(int n) {
		System.out.print(n);
	}
}
